package com.example.springblog.utils;

import com.example.springblog.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

public class JwyUtils {
    private static final String KEY="fbvH5TEANeRAPGAPSrZ5+8N5GQpj6rxjiG/mjmIgF+k=";
    private static final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(KEY));
    public static final long Expiration=12*60*60*1000;
    /*
    * 生成token
    * */
    public static String genJwtToken(Map<String,Object> claim){
        String token= Jwts.builder()
                .setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis()+Expiration))
                .signWith(key)
                .compact();
        return token;
    }
    /*
    * 校验token
    * */
    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims=null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            return null;
        }
       return claims;
    }
    public static Integer getIdByToken(String token){
        Claims claims=parseToken(token);
        if(claims!=null){
            Integer userId=(Integer) claims.get(Constants.TOKEN_ID);
            if (userId>0){
                return userId;
            }
        }
        return null;
    }
}
